package com.stenio.fancat.service.shop;

import com.baomidou.mybatisplus.plugins.Page;
import com.stenio.fancat.domain.baby.BabyAccount;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.shop.FcRedOrder;
import com.stenio.fancat.domain.shop.FcShop;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.domain.user.UserRelationshipFomId;
import com.stenio.fancat.domain.user.UserRelationshipLog;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.shop.RedPacketOrderForm;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.mapper.shop.FcRedOrderMapper;
import com.stenio.fancat.mapper.shop.FcShopMapper;
import com.stenio.fancat.mapper.user.UserRelationshipCandyMapper;
import com.stenio.fancat.mapper.user.UserRelationshipFomIdMapper;
import com.stenio.fancat.mapper.user.UserRelationshipLogMapper;
import com.stenio.fancat.mapper.user.UserRelationshipMapper;
import com.stenio.fancat.payment.PayMent;
import com.stenio.fancat.service.wx.WxPushServiceQcl;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author liuan
 * @create 2019-01-30 14:47
 */
@Service
public class SendRedPacketService {

    @Autowired
    private PayMent payMent;

    @Autowired
    private FcRedOrderMapper fcRedOrderMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private UserRelationshipLogMapper userRelationshipLogMapper;

    @Autowired
    private UserRelationshipCandyMapper userRelationshipCandyMapper;

    @Autowired
    private BabyAccountMapper babyAccountMapper;

    @Autowired
    private FcShopMapper fcShopMapper;

    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    @Autowired
    private UserRelationshipFomIdMapper userRelationshipFomIdMapper;

    @Value("${templatePic_integral}")
    private String templatePicIntegral;

    private static final Logger logger = LoggerFactory.getLogger(CategoryService.class);


    /**
     * 根据订单号查询订单详情
     * @param id
     * @return
     */
    public FcRedOrder getById(String id) {
        return fcRedOrderMapper.selectById(id);
    }


    /**
     * 根据条件查询
     * @param redPacketOrderForm
     * @return
     */
    public Page<FcRedOrder> selectByPage(RedPacketOrderForm redPacketOrderForm){
        FcRedOrder fcRedOrder = new FcRedOrder();
        BeanUtils.copyProperties(redPacketOrderForm,fcRedOrder);
        Page<FcRedOrder> page = new Page<>(redPacketOrderForm.getPageNo(), redPacketOrderForm.getPageSize());
        page.setRecords(fcRedOrderMapper.selectByConditionPage(page,fcRedOrder));
        return page;
    }

    /**
     * 根据用户id查询红包订单方法
     * @param id
     * @return
     */
    public List<FcRedOrder> selectRedOrder(String id) {
        return fcRedOrderMapper.selectRedOrder(id);
    }

    /**
     * 添加红包订单方法
     * @param fcRedOrderForm
     * @return
     * @throws FanCatException
     */
    @Transactional
    public FcRedOrder insert(RedPacketOrderForm fcRedOrderForm) throws FanCatException {
        FcShop fcShop = fcShopMapper.selectById(fcRedOrderForm.getBusinessId());
        if (fcShop.getStock() <= 0) {
            throw new FanCatException("库存不足");
        }
        UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(fcRedOrderForm.getUserId());
        BabyAccount babyAccount = babyAccountMapper.selectById(fcRedOrderForm.getBabyId());
        if(babyAccount.getSurplusCandy() < fcRedOrderForm.getOrderPrice()) {
            throw new FanCatException("糖果币余额不足");
        }
        if(babyAccount.getStatus() == 0) {
            throw new FanCatException("账户已被冻结无法兑换");
        }

        //处理发送逻辑
        boolean flag = true;
        if(fcShop.getSendType() == 3) {
            //根据baby查询所有相关user
            List<BabyRelationship> babyRelationships = babyRelationshipMapper.selectUserListByBabyId(fcRedOrderForm.getBabyId());
            for (BabyRelationship relationship : babyRelationships) {
                List<FcRedOrder> fcRedOrders = fcRedOrderMapper.selectRedOrderByUAndB(relationship.getUserId(),fcRedOrderForm.getBusinessId());
                if(CollectionUtils.isNotEmpty(fcRedOrders)) {
                    throw new FanCatException(" 该现金红包每个宝宝只可兑换一次。");
                }
            }
        }else if(fcShop.getSendType() == 2) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDateTime now = LocalDateTime.now();
            String day = now.format(formatter);
            List<BabyRelationship> babyRelationships = babyRelationshipMapper.selectUserListByBabyId(fcRedOrderForm.getBabyId());
            for (BabyRelationship relationship : babyRelationships) {
                List<FcRedOrder> fcRedOrders = fcRedOrderMapper.selectRedOrderByUAndB(relationship.getUserId(),fcRedOrderForm.getBusinessId());
                if(CollectionUtils.isNotEmpty(fcRedOrders)) {
                    for (FcRedOrder redOrder : fcRedOrders) {
                        LocalDateTime orderDay = LocalDateTime.ofInstant(redOrder.getCreateTime().toInstant(), ZoneId.systemDefault());
                        if(day.equals(orderDay.format(formatter))) {
                            throw new FanCatException("该现金红包每个宝宝一天只可兑换一次，请明天再次兑换。");
                        }
                    }
                }
            }
        }
        //执行发送
        FcRedOrder fcRedOrder = new FcRedOrder();
        if(flag){
            Integer money = (int)(fcShop.getMoney()*100);
            Map<String, String> resultMap = payMent.sendWallet(userRelationship.getOpenId(),money,fcShop.getName());
            if(resultMap.isEmpty()) {
                    throw new FanCatException("红包订单发送失败");
            }
            String currTime = DateUtil.getCurrTime();
            String strRandom = StringUtil.buildRandom(4)+"";
            String id = currTime + strRandom;
            Date date = new Date();
            BeanUtils.copyProperties(fcRedOrderForm,fcRedOrder);
            fcRedOrder.setCreateTime(date);
            fcRedOrder.setUpdateTime(date);
            fcRedOrder.setId(id);
            fcRedOrder.setOrderId(id);
            fcRedOrder.setOrderStatus(1);
            fcRedOrder.setOrderType(3);
            int i = fcRedOrderMapper.insertRedOrder(fcRedOrder);
            if(i>0) {
                fcRedOrder.setPaymentNo(resultMap.get("payment_no"));
                fcRedOrder.setPartnerTradeNo(resultMap.get("partner_trade_no"));
                fcRedOrder.setOrderStatus(2);
                try {
                    fcRedOrder.setSendTime(DateUtil.parse(resultMap.get("payment_time"),"yyyy-MM-dd HH:mm:ss"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                fcRedOrderMapper.updateRedOrder(fcRedOrder);
                //更新库存
                fcShopMapper.updateStock(fcRedOrder.getBusinessId(),1,1);
                //更新个人总金额增-减记录
                userRelationshipCandyMapper.updateReduceCandyById(fcRedOrder.getUserId(),fcRedOrder.getOrderPrice(),fcRedOrder.getBabyId());
                //更新baby金额
                babyAccount.setSurplusCandy(babyAccount.getSurplusCandy()-fcRedOrder.getOrderPrice());
                babyAccountMapper.updateById(babyAccount);
                //新增个人消费记录
                UserRelationshipLog u = new UserRelationshipLog();
                u.setUserId(fcRedOrder.getUserId());
                u.setOperType(2);
                u.setCandy(fcRedOrder.getOrderPrice());
                u.setBeforeCandy(babyAccount.getSurplusCandy());
                u.setAfterCandy(babyAccount.getSurplusCandy()-fcRedOrder.getOrderPrice());
                userRelationshipLogMapper.insert(u);
                String format =  DateUtil.format(date, "yyyy-MM-dd");
                String[] keys = {id,fcShop.getName(),format,fcRedOrder.getOrderPrice().toString(),babyAccount.getSurplusCandy()+""};
                UserRelationshipFomId userRelationshipFomId = userRelationshipFomIdMapper.selectFormIdByUid(fcRedOrder.getUserId());
                if(userRelationshipFomId != null) {
                    wxPushServiceQcl.pushOneUser(userRelationship.getOpenId(),
                            userRelationshipFomId.getFormId(),
                            templatePicIntegral,
                            keys,
                            fcRedOrderForm.getPage());
                    userRelationshipFomIdMapper.modifyFormIdByUid(fcRedOrder.getUserId(),userRelationshipFomId.getFormId());
                }


            }

        }

        return fcRedOrder;
    }



}
